<template>
  <div class="app-container calendar-list-container">
    <basic-container>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane :label="it.label" :name="it.value" v-for="(it,index) in tabList" :key="index">
          <el-row>
            <!-- 左侧 部门-指标 树结构 -->
            <el-col :span="8">
              <div class="user__tree boxsty" v-loading="treeListLoading">
                <!-- 搜索框 -->
                <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable></el-input>
                <!-- 树 -->
                <el-tree ref="tree" :data="aTreeData" :props="defaultProps" :filter-node-method="filterNode"
                         class="filter-tree" node-key="zk" highlight-current :default-expanded-keys="llis" accordion
                         @node-click="getNodeData">

                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <!-- 可操作指标 红色，其他指标 无 -->
                    <span @click="editZb(data)" v-if="data.normDeptId"><i :class="data.normDeptId==userDeptId?'el-icon-s-order red':'el-icon-s-order'"></i>{{ node.label }}</span>
                    <!-- 可操作部门 红色，部门路径 绿色，其他部门 无 -->
                    <span @click="sett=false;" v-else><i :class="'el-icon-s-custom '+(data.id==userDeptId?'red':(deptPath.includes('bm'+data.id+',')?'green':''))"></i>{{ node.label }}</span>
                    <!-- 树节点后 操作按钮 -->
                    <span style="position: absolute;right: 0px">
                      <!-- 新增 -->
                      <el-button type="primary" size="mini" :circle="true" icon="el-icon-circle-plus-outline"
                        v-if="data.normDeptId==userDeptId||data.id==userDeptId" @click.stop="newZb(data)">
                      </el-button>
                      <!-- 移动 -->
                      <el-button type="primary" size="mini" :circle="true" icon="el-icon-share"
                        v-if="data.normDeptId==userDeptId" @click.stop="move(data,'move')">
                      </el-button>
                      <!-- 复制 -->
                      <el-button type="primary" size="mini" :circle="true" icon="el-icon-document-copy"
                        v-if="data.normDeptId" @click="move(data,'copy')">
                      </el-button>
                    </span>
                  </span>

                </el-tree>
              </div>
            </el-col>
            <!-- 右侧 指标表单 -->
            <el-col :span="16" v-show="sett">
              <div class="user__main boxsty filter-container">
                <div class="tabletext">{{ tablett }}</div>
                <div class="box-card">
                  <el-form :ref="'form'+it.value" label-position="right" :model="updata" :rules="rules" label-width="120px">

                    <el-row>
                        <el-form-item label="指标名称" prop="normMc">
                          <el-input v-model="updata.normMc" :disabled="qx" placeholder="请输入名称"/>
                        </el-form-item>
                    </el-row>

                    <el-row>
                      <el-form-item label="指标说明" prop="normSm">
                        <el-input type="textarea" :disabled="qx" v-model="updata.normSm"></el-input>
                      </el-form-item>
                    </el-row>

                    <el-row v-if="tabName=='kaoHe'">
                      <el-form-item label="指标类型" prop="normLx">
                        <el-select style="width: 90%;" :clearable="true" v-model="updata.normLx" placeholder="请选择指标类型">
                          <el-option v-for="item in normLxs " :key="item.value" :label="item.label" :value="item.label"></el-option>
                        </el-select>
                      </el-form-item>
                    </el-row>

                    <el-row>
                      <el-col :span="12" v-if="tabName=='cePing'">
                        <el-form-item label="指标权重" prop="normQz">
                          <el-input-number v-model="updata.normQz" :disabled="qx" :min="0.00" :precision="2" :step="0.1" :max="10"></el-input-number>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12" v-if="tabName=='kaoHe'">
                        <el-form-item label="指标单位" prop="normFz" :rules="{ required: true, message: '请填写指标单位', trigger: 'blur' }">
                          <el-input v-model="updata.normFz" placeholder="指标单位"></el-input>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="排序" prop="normPx">
                          <el-input-number v-model="updata.normPx" :disabled="qx" :min="0" :step="1" :max="99"></el-input-number>
                        </el-form-item>
                      </el-col>
                    </el-row>

                    <el-row v-if="tabName=='cePing'">
                      <el-divider></el-divider>
                      <span style="font-size: 20px;">指标分值</span>
                      <el-link icon="el-icon-upload2" type="primary" @click="fzOutData" :underline="false" style="float: right">导出</el-link>
                      <el-link icon="el-icon-download" type="primary" @click="fzInData" :underline="false" style="float: right;margin-right: 10px" v-if="!qx">导入</el-link>

                      <table style="width:100%;border-collapse: collapse;border:1px solid #dae1e7;margin-top: 30px" border="1" cellspacing="0" cellpadding="0">
                        <thead style="display: table;width: 100%;table-layout: fixed;margin-right: 15px">
                          <!--表头列-->
                          <tr>
                            <td align="center" width="80px">序号</td>
                            <td height="40" align="center">分值名称</td>
                            <td align="center" width="170px">分值</td>
                            <td align="center" width="100px" v-if="!qx">
                              <el-button style="margin-left:10px" @click="add()"><i class="el-icon-circle-plus-outline"></i> 添加</el-button>
                            </td>
                            <td width="13px"></td>
                          </tr>
                        </thead>
                        <tbody style="display: block;height: 300px;overflow-y: scroll">
                          {{ normFzData.length == '0' ? "暂无数据" : null }}
                          <tr style="cursor:move;display: table;width: 100%;table-layout: fixed;height: 60px"
                              v-for="(p,id) in normFzData" :key="id" v-dragging="{ item: p, list: normFzData, group: 'normFzData' }">

                            <td align="center" width="80px">{{ id + 1 }}</td>

                            <td height="40" align="center">
                              <el-input v-model="p.fzMc" clearable @focus.stop="select($event)" :disabled="qx"></el-input>
                            </td>

                            <td align="center" width="170px">
                              <el-input-number v-model="p.fz" :min="0.00" :precision="2" :step="1" :max="100" :disabled="qx"></el-input-number>
                            </td>

                            <td align="center" width="100px" v-if="!qx">
                              <el-button style="margin-left:10px" @click="handleDelete(id,p)"><i class="el-icon-delete"></i>移除</el-button>
                            </td>

                          </tr>
                        </tbody>
                      </table>
                    </el-row>

                    <el-form-item v-if="!qx" style="float: right">
                      <el-button type="primary" @click="create('form'+it.value)">保存</el-button>
                      <el-button type="danger" @click="deletet">删除</el-button>
                    </el-form-item>

                  </el-form>
                </div>
              </div>
            </el-col>

          </el-row>
        </el-tab-pane>

        <el-tab-pane label="测评项管理" name="cpxgl"><cpxgl></cpxgl></el-tab-pane>
        <el-tab-pane label="评分规则管理" name="pfgzgl"><pfgzgl></pfgzgl></el-tab-pane>
        <el-tab-pane label="评价等次管理" name="pjdcgl"><pjdcgl></pjdcgl></el-tab-pane>

      </el-tabs>
    </basic-container>
    <!-- 移动复制弹框对话框 -->
    <el-dialog :title="titlet" :visible.sync="visible" :close-on-click-modal="false">
      <el-tree ref="treeB" :data="bTreeData" :props="defaultProps" node-key="zk" :default-expanded-keys="['bm'+userDeptId]"
               class="filter-tree" :highlight-current="true" accordion @node-click="getNodeDataB">

        <span class="custom-tree-node" slot-scope="{ node, data }">
          <!-- 可移动至的指标 红色, 不可移动至的指标 无-->
          <span v-if="data.normDeptId"><i :class="'el-icon-s-order '+(data.normDeptId==userDeptId?'red':'')"></i>{{ node.label }}</span>
          <!-- 可移动至的部门 红色，部门路径 绿色，其他 无-->
          <span v-else><i :class="'el-icon-s-custom '+(data.id==userDeptId?'red':(deptPath.includes('bm'+data.id)?'green':''))"></i>{{ node.label }}</span>
        </span>

      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="ydZb">确定</el-button>
        <el-button @click="visible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 导入导出弹框对话框 -->
    <el-dialog :title="inOutType" :visible.sync="inOutVis">
      <el-main style="max-height:60vh">
        <el-input type="textarea" v-model="fzCopy" style="margin-bottom: 10px" autosize></el-input>
        <el-button type="plain" style="float: right" @click="inOutVis=false">取消</el-button>
        <el-button type="primary" style="float: right;margin-right: 10px" @click="copyButton()" v-if="inOutType=='导入'">保存</el-button>
      </el-main>
    </el-dialog>
  </div>
</template>

<script>
/*!
 * 新配置指标库
 *
 * @author lxl
 * @date 2021-9-3 09:46:52
 */
import {mapGetters} from 'vuex'
//测评
import {addObj, putObj, copyZb, removeZb, moveZb, aTree, bTree} from '@/api/admin/sysnormceping';
//考核
import {addObjB, putObjB, copyZbB, removeZbB, moveZbB, aTreeB, bTreeB} from '@/api/admin/sysnormkaohe';
//测评项管理
import cpxgl from '@/views/ceping/cepingxmxxb/index'
//评分规则管理
import pfgzgl from '@/views/ceping/cepinggzxxb/index'
//评价等次管理
import pjdcgl from '@/views/ceping/cepingdjxxb/index'
//指标类型-下拉数据
import {remote as remoteDict} from '@/api/admin/dict'

export default {
  components: {
    cpxgl,
    pfgzgl,
    pjdcgl
  },
  data() {
    return {
      //标签页
      tabList: [
        {label: "测评指标", value: "cePing"},
        {label: "考核指标", value: "kaoHe"},
      ],
      activeName: 'cePing',
      tabName: 'cePing',

      //导入导出
      inOutType: "",
      inOutVis: false,
      fzCopy: "",

      //指标表单
      updata: {
        normId: '',
        normPid: 0,
        normPath: '',
        normDeptId: '',
        normMc: '',
        normQz: '',
        normLx: '',
        normFz: '',
        normSm: '',
        normPx: '99',
      },
      tablett: '',//表单标题
      sett: false,//表单显示/隐藏
      //表单权限
      qx: false,
      //指标类型-下拉数据
      normLxs: [],
      //分值表格
      normFzData: [],
      //表单规则
      rules: {
        normMc: [
          {required: true, message: '请输入指标名称', trigger: 'blur'},
        ],
        normQz: [
          {required: true, message: '请输入指标权重', trigger: 'blur'},
        ],
        normLx: [
          {required: true, message: '请选择指标类型', trigger: 'change'},
        ],
        normSm: [
          {required: true, message: '请输入指标说明', trigger: 'blur'},
        ],
      },
      userDeptId: '',//用户部门id
      userDeptName: '',//用户部门名称
      deptPath: '',//用户所在部门路径

      //移动/复制
      yds: '',
      ydz: '',
      moveType: '',
      warnText: '',
      typeB: '',
      titlet: '',//弹窗标题
      copyData: [],
      visible: false,

      //树数据
      aTreeData: [],
      bTreeData: [],
      filterText: "",//树过滤
      llis: [],//默认展开
      treeListLoading: true,
      defaultProps: {
        children: 'children',
        label: 'name'
      },

    }
  },
  created() {
    this.userDeptId = this.userInfo.deptId;
    this.llis = ["bm" + this.userDeptId];
    this.getATreeData();
  },
  computed: {
    ...mapGetters([
      'elements',
      'permissions',
      'userInfo'
    ])
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  mounted() {
    this.$dragging.$on('dragged', (value) => {
      for (let x = 0; x < this.normFzData.length; x++) {
        this.normFzData[x].px = x;
      }
    })
    remoteDict("sys_norm_tyupe_subtype").then(response => {
      this.normLxs = response.data.data
    })
  },
  methods: {
    //标签页
    handleClick(tab, event) {
      this.treeListLoading = true;
      this.llis = ["bm" + this.userDeptId];
      this.sett = false;
      if (tab) {
        this.tabName = tab.name;
      }
      this.getATreeData();
    },

    //获得焦点全选
    select(event) {
      event.currentTarget.select();
    },
    //行添加
    add() {
      let newData = {
        fzMc: '',
        fz: '',
        px: this.normFzData.length,
      }
      this.normFzData.splice(this.normFzData.length, 0, newData);
    },
    //行删除
    handleDelete(index, row) {
      this.$confirm("是否删除改行数据", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      }).then((res) => {
        this.normFzData.splice(index, 1);
        this.$notify.success('删除成功')
      }).catch((res) => {

      })
    },
    //导入
    fzInData() {
      this.inOutType = "导入";
      this.fzCopy = "";
      this.inOutVis = true;
    },
    //导出
    fzOutData() {
      this.inOutType = "导出"
      this.fzCopy = JSON.stringify(this.normFzData);
      this.inOutVis = true;
    },
    //分值表格数据
    getFzData(data) {
      if (data) {
        this.normFzData = JSON.parse(data);
      } else {
        this.normFzData = [];
      }
    },
    //导入保存按钮
    copyButton() {
      this.normFzData = JSON.parse(this.fzCopy);
      for (let x = 0; x < this.normFzData.length; x++) {
        this.normFzData[x].px = x;
      }
      this.inOutVis = false;
    },

    //移动至按钮
    move(data, type) {
      this.bTreeData[0].children = [];
      this.getBTreeData(data, type);
      this.yds = data;
      this.ydz = ''
      this.visible = true;
      this.warnText = '未选择';
      this.titlet = "移动指标至：";
      this.typeB = type;
    },
    //移动/复制指标确定按钮
    ydZb() {
      if (this.yds && this.ydz && this.typeB == "move") {
        //移动指标
        (this.tabName == "cePing"
            ? moveZb(this.yds.normId, this.ydz, this.moveType)
            : moveZbB(this.yds.normId, this.ydz, this.moveType)
        )
          .then((res) => {
            if (res.data.code == '0') {
              this.$notify.success('移动成功')
              this.visible = false;
              //刷新数据
              this.getATreeData(this.yds.normId, "zb")
            }
          })
      } else if (this.ydz && this.typeB == "copy") {
        //复制指标
        (this.tabName == 'cePing'
            ? copyZb(this.copyData.normId, this.ydz, this.moveType)
            : copyZbB(this.copyData.normId, this.ydz, this.moveType)
        )
          .then((res) => {
            if (res.data.code == '0') {
              this.$notify.success('复制成功')
              this.visible = false;
              //刷新数据
              this.getATreeData()
            }
          })
      } else {
        this.$notify.warning(this.warnText)
      }
    },

    //新增指标
    newZb(data) {
      this.updata.normPid = data.normId || 0;
      this.updata.normId = '';
      if (data.type == "zb") {
        this.updata.normPath = (data.normPath == '0' ? null : (data.normPath + ",")) + data.normId;
      } else if (data.type == "bm") {
        this.updata.normPath = data.normId;
      }
      this.updata.normDeptId = data.normDeptId || data.id;
      this.updata.normMc = '';
      this.updata.normQz = '';
      this.updata.normFz = '';
      this.updata.normLx = '';
      this.normFzData = [];
      this.updata.normSm = '';
      this.updata.normPx = 99;

      this.copyData = data;
      this.tablett = '新增指标'
      this.sett = true;
      this.qx = false;
    },
    //修改指标
    editZb(data) {
      this.copyData = JSON.parse(JSON.stringify(data));
      this.tablett = '指标修改'
      this.sett = true;

      this.updata.normPid = data.normPid;
      this.updata.normId = data.normId;
      this.updata.normDeptId = data.normDeptId || data.normDeptId;
      this.updata.normMc = data.name || data.normMc;
      this.updata.normQz = data.normQz;
      this.updata.normLx = data.normLx;
      this.updata.normSm = data.normSm;
      this.updata.normPx = data.normPx;

      if (this.tabName == 'cePing') {
        this.getFzData(data.normFz);
      } else {
        this.updata.normFz = data.normFz;
      }

      if (this.updata.normDeptId == this.userDeptId) {
        this.tablett = '指标修改'
        this.qx = false;
      } else {
        this.tablett = '指标查看'
        this.qx = true;
      }
    },
    //删除按钮
    deletet() {
      this.$confirm(this.copyData.children.length != '0' ? "该指标下有其他指标，是否一并删除？" : "是否删除指标", "提示", {
        type: "warning",
        confirmButtonText: "确定",
        cancelButtonText: "取消"
      })
        .then((res) => {
          (this.tabName == 'cePing'
              ? removeZb(this.updata.normId)
              : removeZbB(this.updata.normId)
          )
            .then(res => {
              let sj = res.data.data[0];
              if (res.data.code == '0') {
                this.$notify.success('删除成功')
                //删除后刷新树数据并隐藏表单
                if (this.updata.normPid == '0') {
                  //上级是部门
                  this.getATreeData(this.updata.normDeptId, "bm");
                } else if (sj.normId && sj.normId != 0) {
                  //上级是指标
                  this.getATreeData(sj.normId, "zb");
                  this.sett = false;
                }
              }
            });
        })
        .catch((res) => {
          if (res == 'cancel') {
            this.$notify.success('取消删除')
          }
        })
    },
    //保存/更新按钮
    create(formName) {
      this.$refs[formName][0].validate((valid) => {
        if (valid) {

          if (this.tabName == 'cePing') {
            this.updata.normFz = JSON.stringify(this.normFzData);
          }
          if (this.updata.normId) {
            (this.tabName == 'cePing' ? putObj(this.updata) : putObjB(this.updata))
              .then(res => {
                if (res.data.code == '0') {
                  let data = res.data.data;
                  this.$notify.success('修改成功')
                  //刷新数据
                  this.getATreeData(data[0].normId, "zb")
                }
              })
          } else {
            (this.tabName == 'cePing' ? addObj(this.updata) : addObjB(this.updata))
              .then(res => {
                let data = res.data.data;
                if (res.data.code == '0') {
                  this.$notify.success('添加成功')
                  //刷新数据
                  this.getATreeData(data[0].normId, "zb")
                  this.editZb(data[0]);
                }
              })
          }

        }
      });

    },

    //获取A树数据 部门-指标列表
    getATreeData(data, type) {
      (this.tabName == 'cePing' ? aTree() : aTreeB())
        .then(res => {
          this.aTreeData = res.data.data;
          for (let x in res.data.data) {
            this.aTreeBl(res.data.data[x])
          }
          if (type == "zb") {
            this.llis = ["zb" + data];
          }
          if (type == "bm") {
            this.llis = ["bm" + data];
            this.sett = false
          }
          this.treeListLoading = false;
        });
    },
    //遍历A树 部门-指标列表
    aTreeBl(data) {
      if (data.id == this.userDeptId) {
        this.deptPath = data.normPath;
        this.userDeptName = data.name;
        this.bTreeData = [
          {
            name: data.name,
            id: data.id,
            normPath: data.normPath,
            children: [],
            zk: data.zk,
          }
        ];
      }
      if (data.children && data.children.length != '0') {
        for (let x in data.children) {
          this.aTreeBl(data.children[x]);
        }
      }
    },
    //树过滤
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    //点击结点获取数据
    getNodeData(data) {
      //点击指标行查看/修改
      if (data.normDeptId) {
        this.editZb(data);
      }
    },

    //获取B树数据 移动弹窗-部门-指标列表
    getBTreeData(data, type) {
      let id = data.normId;
      if (type == "copy") {
        id = 0;
      }
      (this.tabName == 'cePing' ? bTree(id) : bTreeB(id))
        .then(res => {
          this.bTreeData[0].children = res.data.data
        });
    },
    //复制/移动弹出框中点击结点获取数据
    getNodeDataB(data) {
      if (data.normDeptId == this.userDeptId || data.id == this.userDeptId) {
        this.getDataB(data)
      } else {
        this.warnText = "不可移至此处"
      }
    },
    getDataB(data) {
      this.titlet = this.typeB == "move" ? "移动指标至：" : "复制指标至：";
      this.titlet += this.userDeptName;
      if (data.normDeptId) {
        this.titlet += "—指标：";
        this.ydz = data.normId;
        this.moveType = 'zb';
      } else {
        this.titlet += "—部门：";
        this.ydz = data.id;
        this.moveType = 'bm';
      }
      this.titlet += data.name;
    },
  }
}
</script>

